package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import POJO.Product;
import Sqlfuncation.AllFuncation;
import javafx.scene.control.Alert;

/**
 * Servlet implementation class AddProductServlet
 */
@WebServlet("/AddProductServlet")
public class AddProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddProductServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		Product product = new Product();
		String pid = request.getParameter("pid");
		int id = Integer.valueOf(pid);
		product = AllFuncation.selectById(id);
		HttpSession session = request.getSession();
		List<Product> p = (List<Product>)session.getAttribute("car");
		boolean pan = false;
		for (Product pr : p) {
			if (id == pr.getProductId()) {
				pan = true;
				pr.setNumber(pr.getNumber()+1);
			} 
		}
		if (pan == false) {
			p.add(product);
		}
//		int total = p.size();
//		int num = (int)p.size();
		int num = 0;
		for (Product pr1 : p) {
			num += pr1.getNumber();
		}
		session.setAttribute("car", p);
		
		request.getSession().setAttribute("num", num);
		request.getSession().setAttribute("car", p);
		response.setContentType("application/json;charset=utf-8");
	
		PrintWriter pw = response.getWriter();
		pw.print("{\"num\":" + num + "}");
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
